package net.wexoo.onlinedivelog.reusable.security.spam;

import org.apache.wicket.ajax.AjaxEventBehavior;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.extensions.markup.html.captcha.CaptchaImageResource;
import org.apache.wicket.markup.html.form.RequiredTextField;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.image.Image;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.Model;

public class Captcha extends Panel {
   private static final long serialVersionUID = 1L;

   private ChallengeModel challengeModel = new ChallengeModel();
   private TextField<String> resultTextField;
   private Image captchaImage;

   public Captcha(String id) {
      super(id);

      setDefaultModel(challengeModel);

      captchaImage = buildCaptchaImage();
      add(captchaImage);

      resultTextField = new RequiredTextField<String>("result", new Model<String>(null));
      resultTextField.add(new ChallengeValidator(challengeModel));
      add(resultTextField);
   }

   private Image buildCaptchaImage() {
      Image newCaptchaImage = new Image("challenge", new CaptchaImageResource(challengeModel));
      newCaptchaImage.setOutputMarkupId(true);
      newCaptchaImage.add(new AjaxEventBehavior("onclick") {

         private static final long serialVersionUID = 1L;

         @Override
         protected void onEvent(AjaxRequestTarget target) {
            refreshCaptchaImage(target);
         }
      });
      return newCaptchaImage;
   }

   @Override
   protected void onBeforeRender() {
      clearInputAndResetChallengeModel();

      super.onBeforeRender();
   }

   private void clearInputAndResetChallengeModel() {
      resultTextField.clearInput();
      resultTextField.setModelObject(null);

      challengeModel.reset();
   }

   private void refreshCaptchaImage(AjaxRequestTarget target) {
      clearInputAndResetChallengeModel();
      target.add(resultTextField);

      Image newCaptchaImage = buildCaptchaImage();
      captchaImage.replaceWith(newCaptchaImage);
      captchaImage = newCaptchaImage;
      target.add(captchaImage);
   }
}